<template>
  <div class="page-user-login">
    <van-nav-bar
      left-arrow
      @click-left="$router.back()"
      title="登录"
    ></van-nav-bar>
    <!-- 登录表单 -->
    <van-cell-group>
      <van-field
        v-model="userForm.mobile"
        label="手机号"
        @blur="checkPhone"
        :error-message="errorMsg.mobile"
        placeholder="请输入手机号"
      />
      <van-field
        v-model="userForm.code"
        label="验证码"
        @blur="checkCode"
        :error-message="errorMsg.code"
        placeholder="请输入验证码"
      >
        <template #button>
          <van-button size="small" type="primary">发送验证码</van-button>
        </template>
      </van-field>
    </van-cell-group>
    <div class="btn-box">
      <van-button @click="login" round block type="info">提交</van-button>
    </div>
  </div>
</template>

<script>
// 导入登录后台接口方法
import { login } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  name: 'user-chat',
  data () {
    return {
      // 登录数据
      userForm: {
        mobile: '13911111111',
        code: '246810'
      },
      // 格式校验提示
      errorMsg: {
        mobile: '',
        code: ''
      }
    }
  },
  methods: {
    ...mapMutations(['setToken']),
    async login () {
      // 1. 校验
      this.checkPhone()
      this.checkCode()
      const { mobile, code } = this.errorMsg
      if (mobile || code) return
      // 2. 通过=》调用接口发送请求
      console.log('调用登录接口！')
      try {
        const { data } = await login(this.userForm)
        // 存储到vuex=》store
        this.setToken(data)
        // 登录成功提示
        this.$toast.success('登录成功！')
        // 跳转页面：上次访问的页面
        const { redirectUrl } = this.$route.query
        if (redirectUrl) {
          this.$router.replace(redirectUrl)
        } else {
          this.$router.replace('/user')
        }
      } catch (error) {
        // console.log(error)
        this.$toast.fail('手机号或验证码错误！')
      }
    },
    // 校验手机号格式
    checkPhone () {
      const { mobile } = this.userForm
      const regPhone = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (!mobile) {
        this.errorMsg.mobile = '手机号必填！'
      } else if (!regPhone.test(mobile)) {
        this.errorMsg.mobile = '手机格式不正确！'
      } else {
        this.errorMsg.mobile = ''
      }
    },
    checkCode () {
      const { code } = this.userForm
      const regCode = /^\d{6}$/
      if (!code) {
        this.errorMsg.code = '验证码必填！'
      } else if (!regCode.test(code)) {
        this.errorMsg.code = '验证码格式不正确！'
      } else {
        this.errorMsg.code = ''
      }
    }
  }
}
</script>

<style scoped lang='less'>
.btn-box {
  margin: 10px;
  .van-button {
    height: 35px;
  }
}
</style>
